# -*- coding: utf-8 -*-
import datetime
import math
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urljoin, json, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class JiangsuWuxiPolicy(BaseTaxPolicySpider):
    name = 'jiangsu_wuxi_policy'

    province = '江苏省'
    city = '无锡市'
    # county = ''
    park = ''

    def __init__(self, get_next=False, **kwargs):
        super().__init__(**kwargs)
        print(get_next)
        self.get_next = get_next

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 500, 200, 202, 502, 429, 521],
                # "DOWNLOAD_DELAY": 5,
                "DOWNLOADER_MIDDLEWARES": {
                    "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                    **downloader_middlewares
                }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['无锡市人民政府', "", "https://www.wuxi.gov.cn/zfxxgk/szfxxgkml/fgwjjjd/zfwj/szfwj/index.shtml"],
            ['无锡市人民政府', "", "https://www.wuxi.gov.cn/zfxxgk/szfxxgkml/fgwjjjd/zfwj/szfbgswj/index.shtml"],
            ['无锡市人民政府', "", "https://www.wuxi.gov.cn/zfxxgk/szfxxgkml/fgwjjjd/zfwj/bmgfxwj/index.shtml"],
            ['无锡市人民政府', "", "https://www.wuxi.gov.cn/zfxxgk/szfxxgkml/fgwjjjd/dwwj/swwj/index.shtml"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item}, dont_filter=True)

    def parse_list(self, response, **kwargs):
        meta = response.meta
        prev_item = meta.get('item')
        elem_list = response.xpath(
            "//div[@class='item']//a[(contains(@href, 'htm') and @title) and not(starts-with(text(), '|'))]/ancestor::div[string-length(string(.))>=5] | "
            "//ul[@class]//li//a[(contains(@href, 'htm') and @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=5] | "
            "//tr//a[(contains(@href, 'htm') and @title) and not(starts-with(text(), '|'))]/ancestor::tr[string-length(string(.))>=9]"
        )

        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a[@title]/@href""").get()
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("./span/text()").get()
            if item['publish_date'] < '2022-01-01':
                # self.get_next = None
                pass
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if 'htm' not in item['source_url']:
                continue
            if 'relativeInfo' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if (self.get_next or self.get_next == '0') and meta.get('is_next') is not False:
            total_page = int(response.xpath(".").re_first(r'pageCount"\s*:\s*"(\d+)"') or 0)
            print(response.url, 'total', total_page, )
            for page_num in range(2, total_page + 1):
                meta.update({'item': prev_item, 'is_next': False})
                # print(params)
                yield scrapy.Request(url=response.url.replace(".shtml", f"_{page_num}.shtml"), callback=self.parse_list, meta=meta)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath(
        #     """string(//meta[@name='PubDate']/@content)""").get() or response.xpath(
        #     "//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl jiangsu_wuxi_policy -a get_next=0".split())
